<template>
  <div class="main-content">
    <AsyncSearchTable :columns="allColumns"
                      :search-items="searchItems"
                      :fetch-data="fetchPosts">
      <template #status="{ row }">
        <el-tag :type="row.status === '0' ? 'success' : 'danger'">
          {{ row.status === '0' ? '正常' : '停用' }}
        </el-tag>
      </template>
      <template #toolbar>
        <el-button type="primary" :icon="Plus" @click="visible = true">新增</el-button>
        <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
      </template>
      <template #action-column>
        <el-button type="info" link :icon="View">查看</el-button>
        <el-button type="primary" link :icon="Edit">编辑</el-button>
        <el-button type="danger" link :icon="Delete">删除</el-button>
      </template>
    </AsyncSearchTable>

    <el-dialog
        :model-value="visible"
        @update:model-value="$emit('update:visible', $event)"
        title="新增岗位"
        width="500px"
    >
      <div>新增岗位表单</div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import AsyncSearchTable from '@/components/AsyncSearchTable/index.vue'
import * as http from "@/api/http.ts"
import {Delete, Edit, Plus, View} from "@element-plus/icons-vue"
import type {SearchItem} from "@/types/search.ts"

// 表格多选相关
const selectedRows = ref<any[]>([])
// 所有可用的列配置
const allColumns = [
  {prop: 'postCode', label: '岗位编码', width: 120},
  {prop: 'postName', label: '岗位名称', width: 150},
  {prop: 'postSort', label: '显示顺序', width: 150},
  {prop: 'status', label: '状态', width: 150},
  {prop: 'createdTime', label: '创建时间', width: '180'},
  {prop: 'createdBy', label: '创建人', width: '120'},
  {prop: 'remark', label: '备注', width: '200'}
]

const visible = ref(false)

const fetchPosts = async () => {
  try {
    const response = await http.get('/api/posts')
    return response.data
  } catch (error) {
    console.error('获取岗位列表失败', error)
    return []
  }
}

// 状态选项
const statusOptions = [
  {label: '全部', value: ''},
  {label: '正常', value: '0'},
  {label: '停用', value: '1'}
]

// 搜索项配置
const searchItems: SearchItem[] = [
  {
    field: 'postCode',
    label: '岗位编码',
    type: 'input',
    placeholder: '请输入岗位编码'
  },
  {
    field: 'postName',
    label: '岗位名称',
    type: 'input',
    placeholder: '请输入岗位名称'
  },
  {
    field: 'status',
    label: '状态',
    type: 'select',
    options: statusOptions
  },
  {
    field: 'createdTime',
    label: '创建时间',
    type: 'date'
  }
]

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm('确认删除所选岗位记录?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际开发中会调用删除接口
    ElMessage.success('删除成功')
  }).catch(() => {
  })
}
</script>

<style scoped>
</style> 